package com.ruoyi.settled.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.settled.domain.SettlementStatus;
import com.ruoyi.settled.helper.SettlementUtils;
import com.ruoyi.settled.mapper.SettlementAgreementMapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.settled.domain.SettlementDetail;
import com.ruoyi.settled.domain.SettlementRecord;
import com.ruoyi.settled.mapper.SettlementDetailMapper;
import com.ruoyi.settled.mapper.SettlementRecordMapper;
import com.ruoyi.settled.service.ISettlementRecordService;
import com.ruoyi.settled.helper.SettlementCalculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 结算记录Service业务层处理
 * 
 * @author huangchen
 * @date 2025-01-05
 */
@Service
public class SettlementRecordServiceImpl implements ISettlementRecordService 
{
    @Autowired
    private SettlementRecordMapper settlementRecordMapper;

    @Autowired
    private SettlementAgreementMapper settlementAgreementMapper;

    @Autowired
    private SettlementDetailMapper settlementDetailMapper;

    @Autowired
    private SettlementCalculator settlementCalculator;

    @Autowired
    private SettlementUtils settlementUtils;


    // 内存中的自增计数器，实际应用中应使用数据库序列
    private static int recordCounter = 0;

    /**
     * 查询结算记录
     * 
     * @param settlementCode 结算记录主键
     * @return 结算记录
     */
    @Override
    public SettlementRecord selectSettlementRecordBySettlementCode(String settlementCode)
    {
        SettlementRecord record = settlementRecordMapper.selectSettlementRecordBySettlementCode(settlementCode);
        // 查询结算明细
        List<SettlementDetail> details =  settlementDetailMapper.selectSettlementDetailBySettlementCode(settlementCode);
        System.out.println("Settlement Detail List: " + details);
        // 将明细数据放入记录对象
        record.setSettlementDetailList(details);
        return record;
    }

    /**
     * 查询结算记录列表
     * 
     * @param settlementRecord 结算记录
     * @return 结算记录
     */
    @Override
    public List<SettlementRecord> selectSettlementRecordList(SettlementRecord settlementRecord)
    {
        return settlementRecordMapper.selectSettlementRecordList(settlementRecord);
    }

    /**
     * 新增结算记录
     * 
     * @param settlementRecord 结算记录
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSettlementRecord(SettlementRecord settlementRecord) {
        // 验证 agreement_code 是否存在
        if (StringUtils.isEmpty(settlementRecord.getAgreementCode()) ||
                settlementAgreementMapper.existsByAgreementCode(settlementRecord.getAgreementCode()) == 0) {
            throw new IllegalArgumentException("Invalid agreement_code: " + settlementRecord.getAgreementCode());
        }

        // 设置默认的 start_date 值
        if (settlementRecord.getStartDate() == null) {
            settlementRecord.setStartDate(new Date());
        }

        // 设置默认的 end_date 值，为 start_date 加上 14 天
        if (settlementRecord.getEndDate() == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(settlementRecord.getStartDate());
            calendar.add(Calendar.DAY_OF_MONTH, 14);
            settlementRecord.setEndDate(calendar.getTime());
        }


//        if (StringUtils.isEmpty(settlementRecord.getCreator())) {
//            settlementRecord.setCreator("结算人A");
//        }

        // 修改后（获取当前用户）：
        if (StringUtils.isEmpty(settlementRecord.getCreator())) {
            String username = SecurityUtils.getUsername();
            if (StringUtils.isEmpty(username)) {
                throw new RuntimeException("无法获取当前登录用户");
            }
            settlementRecord.setCreator(username);
        }

        // 设置默认的 settlement_type 值
        if (StringUtils.isEmpty(settlementRecord.getSettlementType())) {
            settlementRecord.setSettlementType("A");
        }

        // 设置默认的 settlement_status 值
        if (StringUtils.isEmpty(settlementRecord.getSettlementStatus())) {
            settlementRecord.setSettlementStatus("待确认");
        }

        // 设置默认的 modify_time 值
        if (settlementRecord.getModifyTime() == null) {
            settlementRecord.setModifyTime(new Date());
        }

        // 计算结算金额
        BigDecimal orderAmount = settlementRecord.getOrderAmount(); // 假设结算记录中有订单金额字段
        String partnerCode = settlementRecord.getPartnerCode(); // 假设结算记录中有合作方编码字段
        BigDecimal settlementAmount = settlementUtils.calculateSettlementByPartnerCode(orderAmount, partnerCode);
        settlementRecord.setSettlementAmount(settlementAmount); // 设置结算金额到结算记录对象中

        // 生成带有前缀 Record 的唯一 settlement_code
        String settlementCode = "Record" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6);
        settlementRecord.setSettlementCode(settlementCode);

        int rows = settlementRecordMapper.insertSettlementRecord(settlementRecord);
        insertSettlementDetail(settlementRecord);
        return rows;
    }

    /**
     * 修改结算记录
     * 
     * @param settlementRecord 结算记录
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSettlementRecord(SettlementRecord settlementRecord)
    {
        settlementRecordMapper.deleteSettlementDetailBySettlementCode(settlementRecord.getSettlementCode());
        insertSettlementDetail(settlementRecord);
        return settlementRecordMapper.updateSettlementRecord(settlementRecord);
    }

    /**
     * 批量删除结算记录
     * 
     * @param settlementCodes 需要删除的结算记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSettlementRecordBySettlementCodes(String[] settlementCodes)
    {
        settlementRecordMapper.deleteSettlementDetailBySettlementCodes(settlementCodes);
        return settlementRecordMapper.deleteSettlementRecordBySettlementCodes(settlementCodes);
    }

    /**
     * 删除结算记录信息
     * 
     * @param settlementCode 结算记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSettlementRecordBySettlementCode(String settlementCode)
    {
        settlementRecordMapper.deleteSettlementDetailBySettlementCode(settlementCode);
        return settlementRecordMapper.deleteSettlementRecordBySettlementCode(settlementCode);
    }

    /**
     * 根据合作方编码获取结算记录信息
     *
     * @param partnerCode 合作方编码
     * @return 结果
     */
    @Override
    public List<SettlementRecord> selectRecordInfoByPartnerCode(String partnerCode) {
        List<SettlementRecord> records = settlementRecordMapper.selectSettlementRecordByPartnerCode(partnerCode);
        return records;
    }

    @Override
    public void confirmSettlement(String settlementCode) {
        // 查询结算单
        SettlementRecord settlementRecord = settlementRecordMapper.selectSettlementRecordBySettlementCode(settlementCode);
        if (settlementRecord == null) {
            throw new RuntimeException("结算单不存在");
        }

        // 检查当前状态是否为“待确认”
        if (!SettlementStatus.PENDING_CONFIRM.getDescription().equals(settlementRecord.getSettlementStatus())) {
            throw new RuntimeException("当前状态不允许确认");
        }

        // 更新状态为“待支付”
        settlementRecord.setSettlementStatus(SettlementStatus.PENDING_PAYMENT.getDescription());
        settlementRecordMapper.updateRecordStatus(settlementRecord);
    }

    @Override
    public void completeSettlement(String settlementCode) {
// 查询结算单
        SettlementRecord settlementRecord = settlementRecordMapper.selectSettlementRecordBySettlementCode(settlementCode);
        if (settlementRecord == null) {
            throw new RuntimeException("结算单不存在");
        }

        // 检查当前状态是否为“待支付”
        if (!SettlementStatus.PENDING_PAYMENT.getDescription().equals(settlementRecord.getSettlementStatus())) {
            throw new RuntimeException("当前状态不允许完成");
        }

        // 更新状态为“已完成”
        settlementRecord.setSettlementStatus(SettlementStatus.COMPLETED.getDescription());
        settlementRecordMapper.updateRecordStatus(settlementRecord);
    }

    @Override
    public void rejectSettlement(String settlementCode, String rejectReason) {
// 查询结算单
        SettlementRecord settlementRecord = settlementRecordMapper.selectSettlementRecordBySettlementCode(settlementCode);
        if (settlementRecord == null) {
            throw new RuntimeException("结算单不存在");
        }

        // 检查当前状态是否为“待确认”
        if (!SettlementStatus.PENDING_CONFIRM.getDescription().equals(settlementRecord.getSettlementStatus())) {
            throw new RuntimeException("只有待确认的结算单可以被驳回");
        }

        // 更新状态为“被驳回”，并设置驳回原因
        settlementRecord.setSettlementStatus(SettlementStatus.REJECTED.getDescription());
        settlementRecord.setRemark(rejectReason);
        settlementRecordMapper.updateRecordStatus(settlementRecord);
    }


    /**
     * 新增结算详情信息
     * 
     * @param settlementRecord 结算记录对象
     */
//    public void insertSettlementDetail(SettlementRecord settlementRecord)
//    {
//        List<SettlementDetail> settlementDetailList = settlementRecord.getSettlementDetailList();
//        String settlementCode = settlementRecord.getSettlementCode();
//        if (StringUtils.isNotNull(settlementDetailList))
//        {
//            List<SettlementDetail> list = new ArrayList<SettlementDetail>();
//            for (SettlementDetail settlementDetail : settlementDetailList)
//            {
//                settlementDetail.setSettlementCode(settlementCode);
//                list.add(settlementDetail);
//            }
//            if (list.size() > 0)
//            {
//                settlementRecordMapper.batchSettlementDetail(list);
//            }
//        }
//    }
    private void insertSettlementDetail(SettlementRecord settlementRecord) {
        List<SettlementDetail> settlementDetailList = settlementRecord.getSettlementDetailList();
        if (StringUtils.isNotNull(settlementDetailList)) {
            String settlementCode = settlementRecord.getSettlementCode();
            settlementDetailList.forEach(detail -> {
                detail.setSettlementCode(settlementCode);
                // 确保 orderAmount 有值
                if (detail.getOrderAmount() == null) {
                    detail.setOrderAmount(BigDecimal.ZERO); // 默认值
                }
            });
            settlementDetailMapper.batchInsertSettlementDetail(settlementDetailList);
        }
    }
}
